//
//  TIMElem+ShowAPIs.m
//  TIMChat
//
//  Created by AlexiChen on 16/3/8.
//  Copyright © 2016年 AlexiChen. All rights reserved.
//

#import "TIMElem+ShowAPIs.h"
#import "NSMutableAttributedString+MHMoment.h"

@implementation TIMElem (ShowAPIs)

- (Class)showCellClassOf:(IMAMsg *)msg
{
    return [ChatBaseTableViewCell class];
}

- (CGSize)sizeInWidth:(CGFloat)width atMsg:(IMAMsg *)packMsg
{
    return CGSizeMake(width, 32);
}

@end


@implementation TIMTextElem (ShowAPIs)

- (Class)showCellClassOf:(IMAMsg *)msg
{
    return [ChatTextTableViewCell class];
}

- (CGSize)sizeInWidth:(CGFloat)width atMsg:(IMAMsg *)packMsg
{
    
    
    YYTextContainer *contentLableContainer = [YYTextContainer containerWithSize:CGSizeMake(width, MAXFLOAT)];
    contentLableContainer.maximumNumberOfRows = 0;
    TIMTextElem *elem = (TIMTextElem *)[packMsg.msg getElem:0];
    
    NSMutableAttributedString *textAttr = [[NSMutableAttributedString alloc] initWithString:[elem text]];
     textAttr.yy_font = MHRegularFont_14;
    [textAttr mh_regexContentWithWithEmojiImageFontSize:14];
   
    YYTextLayout *contentLableLayout = [YYTextLayout layoutWithContainer:contentLableContainer text:textAttr.copy];
   CGSize  contentLableSize = contentLableLayout.textBoundingSize;
    
//    CGSize size = [self.text textSizeIn:CGSizeMake(width, HUGE_VAL) font:[packMsg textFont]];
    
    if (contentLableSize.height < kIMAMsgMinHeigth)
    {
        contentLableSize.height = kIMAMsgMinHeigth;
    }
    return contentLableSize;
}

@end



@implementation TIMImageElem (ShowAPIs)

- (CGSize)getThumbShowSizeInMsg:(IMAMsg *)packMsg;
{
    NSInteger tw = [packMsg integerForKey:kIMAMSG_Image_ThumbWidth];
    NSInteger th = [packMsg integerForKey:kIMAMSG_Image_ThumbHeight];
    
    if (tw == 0 || th == 0)
    {
        BOOL succ = NO;
        for (TIMImage *timImage in self.imageList)
        {
            if (timImage.type == TIM_IMAGE_TYPE_THUMB)
            {
                // 解析大小
                CGFloat scale = 1;
                scale = MIN(kChatPicThumbMaxHeight/timImage.height, kChatPicThumbMaxWidth/timImage.width);
                tw = (NSInteger)(timImage.width * scale + 1);
                th =  (NSInteger)(timImage.height * scale + 1);
                
                [packMsg addInteger:tw forKey:kIMAMSG_Image_ThumbWidth];
                [packMsg addInteger:th forKey:kIMAMSG_Image_ThumbHeight];
                succ = YES;
                break;
            }
        }
    }
    
    return CGSizeMake(tw, th);
}


- (Class)showCellClassOf:(IMAMsg *)msg
{
    return [ChatImageTableViewCell class];
}

- (CGSize)sizeInWidth:(CGFloat)width atMsg:(IMAMsg *)packMsg
{
    NSInteger tw = [packMsg integerForKey:kIMAMSG_Image_ThumbWidth];
    NSInteger th = [packMsg integerForKey:kIMAMSG_Image_ThumbHeight];
    
    if (tw ==0 || th ==0)
    {
        BOOL succ = NO;
        for (TIMImage *timImage in self.imageList)
        {
            if (timImage.type == TIM_IMAGE_TYPE_THUMB)
            {
                // 解析大小
                CGFloat scale = 1;
                scale = MIN(kChatPicThumbMaxHeight/timImage.height, kChatPicThumbMaxWidth/timImage.width);
                tw = (NSInteger)(timImage.width * scale + 1);
                th =  (NSInteger)(timImage.height * scale + 1);
                
                [packMsg addInteger:tw forKey:kIMAMSG_Image_ThumbWidth];
                [packMsg addInteger:th forKey:kIMAMSG_Image_ThumbHeight];
                succ = YES;
                break;
            }
        }
        
        if (!succ)
        {
            NSString *filePath = self.path;
            NSInteger thumbWidth = kChatPicThumbMaxWidth;
            NSInteger thumbHeight = kChatPicThumbMaxHeight;
            if (![NSString isEmpty:filePath])
            {
                // NSString *filePath = [NSString stringWithFormat:@"%@uploadFile%3.f_Size_%d_%d", nsTmpDIr, [NSDate timeIntervalSinceReferenceDate], (int)picThumbWidth, (int)picThumbHeight];
                // 检查本地是否存储了
                BOOL exist = [PathUtility isExistFile:filePath];
                if (exist)
                {
                    // 获取原图
                    UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
                    // TODO：是否能过加载的图片再算
                    CGFloat scale = 1;
                    scale = MIN(kChatPicThumbMaxHeight/image.size.height, kChatPicThumbMaxWidth/image.size.width);
                    
                    CGFloat picHeight = image.size.height;
                    CGFloat picWidth = image.size.width;
                    thumbWidth = (NSInteger)(picHeight * scale + 1);
                    thumbHeight = (NSInteger)(picWidth * scale + 1);
                    
                    tw = thumbWidth;
                    th = thumbWidth;
                    
                    [packMsg addInteger:thumbHeight forKey:kIMAMSG_Image_ThumbHeight];
                    [packMsg addInteger:thumbWidth forKey:kIMAMSG_Image_ThumbWidth];
                }
                else
                {
                    DebugLog(@"程序异常退出，导致本地缓存图片不存在");
                }
            }
            else
            {
                DebugLog(@"理论不可达区域");
            }
        }
    }
    
    
    
    if (tw > width)
    {
        th = (NSInteger)(th * width/tw);
        tw = width;
    }
    
    return CGSizeMake(tw, th);
}

@end

@implementation TIMFileElem (ShowAPIs)


- (Class)showCellClassOf:(IMAMsg *)msg
{
    return [ChatFileTableViewCell class];
}

- (CGSize)sizeInWidth:(CGFloat)width atMsg:(IMAMsg *)packMsg
{
    return CGSizeMake(width, 70);
}
@end

@implementation TIMSoundElem (ShowAPIs)

- (Class)showCellClassOf:(IMAMsg *)msg
{
    return [ChatSoundTableViewCell class];
}

- (CGSize)sizeInWidth:(CGFloat)width atMsg:(IMAMsg *)packMsg
{
    NSInteger minWidth = 70;
    
    NSInteger uni = (width - minWidth)/60;
    
    NSInteger w = minWidth + self.second * uni;
    if (w > width)
    {
        w = width;
    }
    return CGSizeMake(w, kIMAMsgMinHeigth);
}

@end

@implementation TIMFaceElem (ShowAPIs)


// 是否是系统表情(QQ自带的表情)
- (BOOL)isSystemFace
{
    // 目前没有做自定义表情，所以全问都是系统表情
    // 用户可根据自身业务逻辑修改此处
    return YES;
}

@end

@implementation TIMLocationElem (ShowAPIs)

@end

@implementation TIMGroupTipsElem (ShowAPIs)



- (Class)showCellClassOf:(IMAMsg *)msg
{
    return [ChatGroupTipTableViewCell class];
}

- (CGSize)sizeInWidth:(CGFloat)width atMsg:(IMAMsg *)packMsg
{
    TIMGroupTipsElem *elem = (TIMGroupTipsElem *)[packMsg.msg getElem:0];
    CGSize size = [[self tipText] textSizeIn:CGSizeMake(width, HUGE_VALF) font:[packMsg tipFont] breakMode:NSLineBreakByWordWrapping align:NSTextAlignmentCenter];
    size.height <= 40 ? size.height = 40 : size.height;
    if (elem.type != TIM_GROUP_TIPS_TYPE_INVITE) {
        size.height = 0;
    }
    return size;
}

@end

@implementation TIMUGCElem (ShowAPIs)

- (Class)showCellClassOf:(IMAMsg *)msg
{
    return [ChatVideoTableViewCell class];
}

- (CGSize)sizeInWidth:(CGFloat)width atMsg:(IMAMsg *)packMsg
{
    return CGSizeMake(150, 100);
}

@end

NSString const *TIMCustomElem_contentLableLayoutKey = @"TIMCustomElem_contentLableLayoutKey";
NSString const *TIMCustomElem_anserLableLayoutKey = @"TIMCustomElem_anserLableLayoutKey";
NSString const *TIMCustomElem_locationLableLayoutKey = @"TIMCustomElem_locationLableLayoutKey";
@implementation TIMCustomElem (ShowAPIs)


- (Class)showCellClassOf:(IMAMsg *)msg
{
    if (msg.type == EIMAMSG_TimeTip)
    {
        return [ChatTimeTipTableViewCell class];
    }
    else if (msg.type == EIMAMSG_SaftyTip)
    {
        return [ChatSaftyTipTableViewCell class];
    }
    else if (msg.type == EIMAMSG_RevokedTip)
    {
        return [RevokedTipTableViewCell class];
    }
    else if (msg.type == EIMAMSG_Custom)
    {
        TIMElem* elem = [msg.msg getElem:0];
        CustomElemCmd *elemCmd = [[IMAPlatform sharedInstance].conversationMgr  isOnlineMsg:elem];
        MHIMMessageType type  =  [[elemCmd.customInfo objectForKey:@"msgType"] intValue];
        if (type == MHIMMessageTypeRedPacketMessaege || type == MHIMMessageTypeTotalRedPacketMessage || type == MHIMMessageTypeJoinCircleName ) {
            return [ChatGroupTipTableViewCell class];
        }else
        {
            return [ChatCustomVideoImageCell class];
        }
        
    }
    else
    {
        return [super showCellClassOf:msg];
    }
}


-(YYTextLayout *)contentLableLayout
{
     return objc_getAssociatedObject(self, &TIMCustomElem_contentLableLayoutKey);
}

-(void)setContentLableLayout:(YYTextLayout *)contentLableLayout
{
    objc_setAssociatedObject(self, &TIMCustomElem_contentLableLayoutKey, contentLableLayout, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}



-(YYTextLayout *)anserLableLayout
{
    return objc_getAssociatedObject(self, &TIMCustomElem_anserLableLayoutKey);
}

-(void)setAnserLableLayout:(YYTextLayout *)anserLableLayout
{
    objc_setAssociatedObject(self, &TIMCustomElem_anserLableLayoutKey, anserLableLayout, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


-(YYTextLayout *)locationLableLayout
{
    return objc_getAssociatedObject(self, &TIMCustomElem_locationLableLayoutKey);
}


-(void)setLocationLableLayout:(YYTextLayout *)locationLableLayout
{
    objc_setAssociatedObject(self, &TIMCustomElem_locationLableLayoutKey, locationLableLayout, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


- (CGSize)sizeInWidth:(CGFloat)width atMsg:(IMAMsg *)packMsg
{
    
    if (packMsg.type == EIMAMSG_Custom) {
        
        CGFloat height = 0;
        TIMCustomElem *customElem= [packMsg.msg getElem:0];
        NSDictionary *dictJson = [NSJSONSerialization JSONObjectWithData:customElem.data options:NSJSONReadingMutableContainers error:nil];
        NSString *dict = [dictJson objectForKey:@"actionParam"];
        if (!dict) {
            return CGSizeMake(0, 0);
        }
        NSData *objectData = [dict dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
                                                             options:NSJSONReadingMutableContainers
                                                               error:nil];
        
        if (json) {
            MHMoment *moment = [MHMoment yy_modelWithJSON:json];
            CGFloat limitWidth = MHMomentCommentViewWidth() * 0.8 - 20;
            YYTextBorder *border = [YYTextBorder new];
            border.cornerRadius = 0;
            border.insets = UIEdgeInsetsMake(0, -1, 0, -1);
            border.fillColor = MHMomentTextHighlightBackgroundColor;
            
            
            YYTextContainer *singleRowContainer = [YYTextContainer containerWithSize:YYTextContainerMaxSize];
            singleRowContainer.maximumNumberOfRows = 1;
            
            if (moment.recentType != MHRecentContentTypeAsk && MHStringIsEmpty(moment.recentQA.questionContent) ) {
                if (MHStringIsNotEmpty(moment.text)){
                    NSMutableAttributedString *textAttr = [[NSMutableAttributedString alloc] initWithString:moment.text];
                    textAttr.yy_font = MHMomentContentFont;
                    textAttr.yy_color = MHMainTextColor;
//                    textAttr.yy_lineBreakMode = NSLineBreakByTruncatingTail;
                    textAttr.yy_alignment = NSTextAlignmentLeft;
                    [textAttr mh_regexContentWithWithEmojiImageFontSize:15];
                    
                    YYTextContainer *contentLableContainer = [YYTextContainer containerWithSize:CGSizeMake(limitWidth, MAXFLOAT)];
                    contentLableContainer.maximumNumberOfRows = 2;
                    YYTextLayout *contentLableLayout = [YYTextLayout layoutWithContainer:contentLableContainer text:textAttr.copy];
                    self.contentLableLayout = contentLableLayout;
                    
                }
            }else
            {
                //与我相关，向我提问 ，发表后的样子
                //            moment.recentQA.answerContent =  @"222";
                if (MHStringIsNotEmpty(moment.recentQA.questionContent)){
                    NSMutableAttributedString *textAttr = [[NSMutableAttributedString alloc] initWithString:moment.recentQA.questionContent];
                    textAttr.yy_font = MHMomentContentFont;
                    textAttr.yy_color = MHMomentContentTextColor;
                    textAttr.yy_lineBreakMode = NSLineBreakByTruncatingTail;
                    textAttr.yy_alignment = NSTextAlignmentLeft;
                    NSMutableAttributedString *askedAttr;
                    BOOL isReplay = MHStringIsNotEmpty(moment.recentQA.answerContent);
                    NSString *askString =  isReplay ? [NSString stringWithFormat:@"%@提问:",moment.recentQA.questionUserName] : [NSString stringWithFormat:@"向%@提问:", moment.recentQA.answerUserName];
                    if (moment.recentQA.answerUserName.length > 0) {
                        askedAttr = [[NSMutableAttributedString alloc] initWithString:askString];
                        askedAttr.yy_color = MHMomentAskTextColor;
                        askedAttr.yy_font = MHMomentScreenNameFont;
                        askedAttr.yy_alignment = NSTextAlignmentLeft;
                        [textAttr insertAttributedString:askedAttr atIndex:0];
                    }
                    /// 去正则匹配
                    [textAttr mh_regexContentWithWithEmojiImageFontSize:15];
                    YYTextContainer *contentLableContainer = [YYTextContainer containerWithSize:CGSizeMake(limitWidth, MAXFLOAT)];
                    contentLableContainer.maximumNumberOfRows = 2;
                    YYTextLayout *contentLableLayout = [YYTextLayout layoutWithContainer:contentLableContainer text:textAttr.copy];
                    self.contentLableLayout = contentLableLayout;
                }
               
                
                
                if (MHStringIsNotEmpty(moment.recentQA.questionContent) && MHStringIsNotEmpty(moment.recentQA.answerContent))
                {
                    NSMutableAttributedString *textAttr = [[NSMutableAttributedString alloc] initWithString:moment.recentQA.answerContent];
                    textAttr.yy_font = MHMomentContentFont;
                    textAttr.yy_color = MHMomentContentTextColor;
                    textAttr.yy_lineBreakMode = NSLineBreakByTruncatingTail;
                    textAttr.yy_alignment = NSTextAlignmentLeft;
                    UIFont *font = MHMomentCommentScreenNameFont;
                    UIImage *quotationImage = [UIImage imageNamed:@"icon_message_quotation"];
                    quotationImage = [UIImage imageWithCGImage:quotationImage.CGImage scale:[UIScreen screenScale] orientation:UIImageOrientationUp];
                    
                    NSMutableAttributedString *attachLikeText = [NSMutableAttributedString yy_attachmentStringWithContent:quotationImage contentMode:UIViewContentModeCenter attachmentSize:quotationImage.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];
                    NSMutableAttributedString *marginAttr = [[NSMutableAttributedString alloc] initWithString:@"  "];
                    [attachLikeText appendAttributedString:marginAttr];
                    
                    [textAttr insertAttributedString:attachLikeText atIndex:0];
                    //                }
                    /// 去正则匹配
                    [textAttr mh_regexContentWithWithEmojiImageFontSize:15];
                    YYTextContainer *anserLableContainer = [YYTextContainer containerWithSize:CGSizeMake(limitWidth, MAXFLOAT)];
                    anserLableContainer.maximumNumberOfRows = 2;
                    YYTextLayout *anserLableLayout = [YYTextLayout layoutWithContainer:anserLableContainer text:textAttr.copy];
                    self.anserLableLayout = anserLableLayout;
                    height += MHMomentContentInnerMargin;
                }
            }
            height = self.contentLableLayout.textBoundingSize.height + 10;
            height += self.anserLableLayout.textBoundingSize.height;
            if (moment.location.isShowLocation) {
                /// 富文本
                
                UIImage *likeImage = [UIImage imageNamed:@"icon_theme_dividingline"];
                likeImage = [UIImage imageWithCGImage:likeImage.CGImage scale:[UIScreen screenScale] orientation:UIImageOrientationUp];
                
                NSMutableAttributedString *attachLikeText = [NSMutableAttributedString yy_attachmentStringWithContent:likeImage contentMode:UIViewContentModeCenter attachmentSize:likeImage.size alignToFont:MHRegularFont_10 alignment:YYTextVerticalAlignmentCenter];
                
                NSMutableAttributedString *location  = [[NSMutableAttributedString alloc] initWithString:@""];
                [location appendAttributedString:attachLikeText];
                [location appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@"   "]];
                
                UIImage *locationImage = [UIImage imageNamed:@"icon_theme_locationb"];
                locationImage = [UIImage imageWithCGImage:locationImage.CGImage scale:[UIScreen screenScale] orientation:UIImageOrientationUp];
                
                NSMutableAttributedString *attachLocation = [NSMutableAttributedString yy_attachmentStringWithContent:locationImage contentMode:UIViewContentModeCenter attachmentSize:locationImage.size alignToFont:MHRegularFont_10 alignment:YYTextVerticalAlignmentCenter];
                [location appendAttributedString:attachLocation];
                [location appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@" "]];
                [location appendAttributedString:[[NSMutableAttributedString alloc] initWithString:moment.location.areaName]];
                location.yy_font = MHRegularFont_10;
                location.yy_color = MHMetionTextColor;
                /// 高亮
                YYTextHighlight *highlight = [YYTextHighlight new];
                [highlight setBackgroundBorder:border];
                /// 传递数据
                highlight.userInfo = @{MHMomentLocationNameKey : moment.location};
                [location yy_setTextHighlight:highlight range:location.yy_rangeOfAll];
                /// 布局
                YYTextLayout *locationLableLayout = [YYTextLayout layoutWithContainer:singleRowContainer text:location.copy];
                self.locationLableLayout = locationLableLayout;
                height += MHMomentContentInnerMargin;
                height += 25 - 8;
            }

            // 8 是底部高度
            return CGSizeMake(MHMomentCommentViewWidth() *0.8 , height + 8 + MHMomentContentInnerMargin * 2 + 147);
        }

        return CGSizeMake(width, 0);
    }else
    {
        return [super sizeInWidth:width atMsg:packMsg];
    }
    
}

@end


@implementation TIMGroupSystemElem (ShowAPIs)

- (Class)showCellClassOf:(IMAMsg *)msg
{
    return [ChatBaseTableViewCell class];
}

- (CGSize)sizeInWidth:(CGFloat)width atMsg:(IMAMsg *)packMsg
{
    return CGSizeMake(width, 32);
}

@end


@implementation TIMSNSSystemElem (ShowAPIs)


@end

@implementation TIMProfileSystemElem (ShowAPIs)

// 显示描述
- (NSString *)showDescriptionOf:(IMAMsg *)msg
{
    // 后面转成对应的描述信息
    return @"[资料变更消息]";
}
@end
